package wangwenjun.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.*;

/**
 * @auth eric-好好学习，天天向上!
 * @date 2022/5/10
 * @description
 */
public class LambdaUsage {

    private static List<Apple> find(List<Apple> source, Predicate<Apple> predicate) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : source) {
            if (predicate.test(apple)) {
                list.add(apple);
            }
        }

        return list;
    }

    private static List<Apple> filterByWeight(List<Apple> source, IntPredicate predicate) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : source) {
            if (predicate.test(apple.getWeight())) {
                list.add(apple);
            }
        }

        return list;
    }

    private static List<Apple> filterByBiPredicate(List<Apple> source, BiPredicate<String, Integer> biPredicate) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : source) {
            if (biPredicate.test(apple.getColor(), apple.getWeight())) {
                list.add(apple);
            }
        }

        return list;
    }

    private static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer) {
        for (Apple apple : source) {
            consumer.accept(apple);
        }
    }

    private static String testFunction(Apple apple, Function<Apple, String> function) {
        return function.apply(apple);
    }

    private static Apple createApple(Supplier<Apple> supplier) {
        return supplier.get();
    }


    public static void main(String[] args) {
//        Runnable runnable1 = () -> System.out.println("Hello");
//
//        process(runnable1);

        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("yellow", 150));
        System.out.println(find(list, (apple) -> "yellow".equals(apple.getColor())));
        System.out.println(filterByWeight(list, weight -> weight > 100));
        System.out.println(filterByBiPredicate(list, (color, weight) -> weight > 100 && "yellow".equals(color)));
        simpleTestConsumer(list, apple -> System.out.println(apple));

        System.out.println(testFunction(new Apple("red", 120), apple -> "apple: " + apple.getColor() + "_" + apple.getWeight()));

        Apple apple = createApple(() -> new Apple("blue", 129));
        System.out.println(apple.getColor());
 
    }


    public static void process(Runnable runnable) {
        runnable.run();
    }

}
